<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @package 		925CMS
 * @subpackage 		WYSIWYG
 * @author			Phil Sturgeon, Marcos Coelho
 *
 * Manages files selection and insertion for WYSIWYG editors
 */
class Files extends WYSIWYG_Controller {

	public function __construct()
	{
		parent::__construct();
	}

	public function index($id = 0)
	{
        /** @var $data obj */
		$data->libraries			= $this->libraries_m->get_libraries();
		$data->sublibraries		= array();
		$data->current_library	= $id && isset($data->libraries[$id])
								? $data->libraries[$id]
								: ($data->libraries ? current($data->libraries) : array());

		if ($data->current_library)
		{
			$data->current_library->items = $this->file_m
				->order_by('date_added', 'DESC')
				->where('type !=', 'i')
				->get_many_by('library_id', $data->current_library->id);

			$sublibraries = $this->libraries_m->library_tree($data->current_library->id);

			foreach ($sublibraries as $sublirary)
			{
				$data->sublibraries[$sublirary->id] = repeater('&raquo; ', $sublirary->depth) . $sublirary->name;
			}

			// Set a default label
			$data->sublibraries = $data->sublibraries
				? array($data->current_library->id => lang('files.dropdown_root')) + $data->sublibraries
				: array($data->current_library->id => lang('files.dropdown_no_subfolders'));
		}

		// Array for select
		$data->libraries_tree = array();
		foreach ($data->libraries as $library)
		{
			$data->libraries_tree[$library->id] = repeater('&raquo; ', $library->depth) . $library->title;
		}

		$data->file_types = array(
			'a' => lang('files.type_a'),
			'v' => lang('files.type_v'),
			'd' => lang('files.type_d'),
			'i' => lang('files.type_i'),
			'o' => lang('files.type_o')
		);

		$this->template
			->title('Files')
			->build('files/index', $data);
	}

	public function ajax_get_files()
	{
		$file = $this->file_m->get($this->input->post('file_id'));

		$librarys = array();
		if ($library_id = $this->input->post('folder_id'))
		{
			$librarys = $this->libraries_m->get_folder_path($library_id);
		}

		$this->load->view('files/ajax_current', array(
			'file'		=> $file,
			'folders'	=> $librarys
		));
	}
}